//
//  ViewController.m
//  Net2
//
//  Created by niit on 16/3/28.
//  Copyright © 2016年 NIIT. All rights reserved.
//

#import "ViewController.h"
#import <MBProgressHUD.h>
#import <TBXML.h>
#import "Netmanager.h"


@interface ViewController ()
@property (weak, nonatomic) IBOutlet UITextField *userTextField;

@property (weak, nonatomic) IBOutlet UITextField *passwordTextField;

@property (strong,nonatomic) MBProgressHUD *hud;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //http://localhost:8080/MJServer/login?username=123&pwd=123&method=get&type=JSON
    // Do any additional setup after loading the view, typically from a nib.
}
- (IBAction)loginBtn1Pressed:(id)sender {
    NSString *str = [NSString stringWithFormat:@"http://localhost:8080/MJServer/login?username=%@&pwd=%@&method=get&type=JSON",self.userTextField.text,self.passwordTextField.text];
    NSURL *url = [NSURL URLWithString:str];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    //发送请求
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        if (connectionError == nil) {
            NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            NSLog(@"%@",str);
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
            NSLog(@"%@",dict);
            if (dict[@"error"] == nil) {
                //用MBProgress库显示登陆成功 后跳转
                _hud = [[MBProgressHUD alloc] initWithView:self.view];
                [self.view addSubview:_hud];
                _hud.dimBackground = YES;
                _hud.mode = MBProgressHUDModeText;
                
                _hud.labelText = @"登陆成功";
                [_hud showAnimated:YES whileExecutingBlock:^{
                    sleep(1);
                } completionBlock:^{
                    [self performSegueWithIdentifier:@"goto1" sender:nil];
                }];
                
            }
            else{
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"登陆失败" message:nil preferredStyle:UIAlertControllerStyleAlert];
                
                UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    nil;
                }];
                [alert addAction:action];
                [self presentViewController:alert animated:YES completion:nil];
            }
        }
        
        NSLog(@"%@,%@",connectionError,[connectionError localizedDescription]);
        NSString *message = [NSString stringWithFormat:@"连接错误:%@",[connectionError localizedDescription]];
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"错误" message:message preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *aciton = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self dismissViewControllerAnimated:YES completion:nil];
        }];
        [alert addAction:aciton];
        [self presentViewController:alert animated:YES completion:nil];

    }];
    
}
//POST JSON
- (IBAction)loginBtn2Pressed:(id)sender {
    NSString *str = @"http://localhost:8080/MJServer/login";

    NSString *param = [NSString stringWithFormat:@"username=%@&pwd=%@&type",self.userTextField.text,self.passwordTextField.text];
    NSURL *url = [NSURL URLWithString:str];
    
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"POST";
    request.HTTPBody = [param dataUsingEncoding:NSUTF8StringEncoding];
    //发送请求
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        if (connectionError == nil) {
            NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            NSLog(@"%@",str);
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
            NSLog(@"%@",dict);
            if (dict[@"error"] == nil) {
                //用MBProgress库显示登陆成功 后跳转
                _hud = [[MBProgressHUD alloc] initWithView:self.view];
                [self.view addSubview:_hud];
                _hud.dimBackground = YES;
                _hud.mode = MBProgressHUDModeText;
                
                _hud.labelText = @"登陆成功";
                [_hud showAnimated:YES whileExecutingBlock:^{
                    sleep(1);
                } completionBlock:^{
                    [self performSegueWithIdentifier:@"goto1" sender:nil];
                }];
                
            }
            else{
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"登陆失败" message:nil preferredStyle:UIAlertControllerStyleAlert];
                
                UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    nil;
                }];
                [alert addAction:action];
                [self presentViewController:alert animated:YES completion:nil];
            }
            
        }
        else{
            NSLog(@"%@,%@",connectionError,[connectionError localizedDescription]);
            NSString *message = [NSString stringWithFormat:@"连接错误:%@",[connectionError localizedDescription]];
            
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"错误" message:message preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *aciton = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [self dismissViewControllerAnimated:YES completion:nil];
            }];
            [alert addAction:aciton];
            [self presentViewController:alert animated:YES completion:nil];

        }
    }];

}
- (IBAction)loginBtn3Pressed:(id)sender {
    NSString *str = @"http://localhost:8080/MJServer/login";
    NSString *param = [NSString stringWithFormat:@"username=%@&pwd=%@&type=XML",self.userTextField.text,self.passwordTextField.text];
    NSURL *url = [NSURL URLWithString:str];
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    
    request.HTTPMethod = @"POST";
    
    request.HTTPBody = [param dataUsingEncoding:NSUTF8StringEncoding];
    
    _hud = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:_hud];
    _hud.dimBackground = YES;
    _hud.mode = MBProgressHUDModeText;
    _hud.labelText = @"正在登陆";
    
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        if (connectionError == nil) {
            TBXML *xml = [[TBXML alloc] initWithXMLData:data error:nil];
            //得到根节点
            TBXMLElement *root = xml.rootXMLElement;
            //节点的名称
            NSString *elementName = [TBXML elementName:root];
            //节点里的内容
            NSString *info = [TBXML textForElement:root];
            if ([elementName isEqualToString:@"error"]) {
                [_hud removeFromSuperview];
                _hud = nil;
                // 登陆失败 显示错误信息
                NSString *message = [NSString stringWithFormat:@"错误信息:%@",info];
                
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"错误" message:message preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *aciton = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    [self dismissViewControllerAnimated:YES completion:nil];
                }];
                [alert addAction:aciton];
                [self presentViewController:alert animated:YES completion:nil];
            }
            else
            {
                [_hud showAnimated:YES whileExecutingBlock:^{
                    sleep(1);
                } completionBlock:^{
                    [_hud removeFromSuperview];
                    _hud = nil;
                    [self performSegueWithIdentifier:@"goto1" sender:nil];
                }];
            }
            
        }
        else{
            NSLog(@"%@,%@",connectionError,[connectionError localizedDescription]);
            NSString *message = [NSString stringWithFormat:@"连接错误:%@",[connectionError localizedDescription]];
            [_hud removeFromSuperview];
            _hud = nil;
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"错误" message:message preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *aciton = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [self dismissViewControllerAnimated:YES completion:nil];
            }];
            [alert addAction:aciton];
            [self presentViewController:alert animated:YES completion:nil];
        }
    }];
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}


//同步请求封装
- (IBAction)btn5Pressed:(id)sender {
    BOOL one = [Netmanager loginWithName:self.userTextField.text WithPassword:self.passwordTextField.text];
    _hud = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:_hud];
    _hud.dimBackground = YES;
    _hud.mode = MBProgressHUDModeText;
    _hud.labelText = @"正在登陆";
    if (one == YES) {
        [_hud showAnimated:YES whileExecutingBlock:^{
            sleep(1);
        } completionBlock:^{
            [_hud removeFromSuperview];
            _hud = nil;
            [self performSegueWithIdentifier:@"goto1" sender:nil];
        }];
    }
    else{
        [_hud removeFromSuperview];
        _hud = nil;
//        // 登陆失败 显示错误信息
//        NSString *message = [NSString stringWithFormat:@"错误信息:%@",info];
//        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"错误" message:nil preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *aciton = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self dismissViewControllerAnimated:YES completion:nil];
        }];
        [alert addAction:aciton];
        [self presentViewController:alert animated:YES completion:nil];
    }
}
- (IBAction)btn6Pressed:(id)sender {
    _hud = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:_hud];
    _hud.dimBackground = YES;
    _hud.mode = MBProgressHUDModeText;
    _hud.labelText = @"正在登陆";
    
    [Netmanager loginWithUserName:self.userTextField.text
                     WithPassword:self.passwordTextField.text
                 WithSuccessBlock:^{
                     [_hud showAnimated:YES whileExecutingBlock:^{
                         sleep(1);
                     } completionBlock:^{
                         [_hud removeFromSuperview];
                         _hud = nil;
                         [self performSegueWithIdentifier:@"goto1" sender:nil];
                     }];
                 }
                  WithFailedBlock:^(NSError *error) {
                      [_hud removeFromSuperview];
                       _hud = nil;
                      NSString *message = [NSString stringWithFormat:@"错误信息:%@",[error localizedDescription]];
                      // 登陆失败 显示错误信息
                      UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"错误" message:message preferredStyle:UIAlertControllerStyleAlert];
                      UIAlertAction *aciton = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                          [self dismissViewControllerAnimated:YES completion:nil];
                      }];
                      [alert addAction:aciton];
                      [self presentViewController:alert animated:YES completion:nil];
                  }];
    
}
- (IBAction)btn7Pressed:(id)sender {
    _hud = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:_hud];
    _hud.dimBackground = YES;
    _hud.mode = MBProgressHUDModeText;
    _hud.labelText = @"正在登陆";
    Netmanager *net = [Netmanager shareNetmanager];
    net.delegate = self;
    [net loginWithUserName:self.userTextField.text WithPassword:self.passwordTextField.text];
}

-(void)loginSuccess{
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [_hud removeFromSuperview];
        _hud = nil;
        [self performSegueWithIdentifier:@"goto1" sender:nil];
    });
}
-(void)loninFail:(NSError *)error{
    [_hud removeFromSuperview];
    _hud = nil;
    NSString *message = [NSString stringWithFormat:@"错误信息:%@",[error localizedDescription]];
    // 登陆失败 显示错误信息
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"错误" message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *aciton = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //[self dismissViewControllerAnimated:YES completion:nil];
        [self dismissViewControllerAnimated:YES completion:nil];
    }];
    [alert addAction:aciton];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
